package com.holy.sh.module_base_mvp.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonTools {

	/**
	 * 获取字符串宽度
	 * @param context
	 * @param text
	 * @param textSize
     * @return
     */
	public static int getTextWidth(Context context, String text, int textSize){
		TextPaint paint = new TextPaint();
		float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
		paint.setTextSize(scaledDensity * textSize);
		return (int) paint.measureText(text);
	}

	/**
	 * dp 转像素单位
	 *
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 像素转化dip
	 *
	 * @param context
	 * @param pxValue
	 * @return
	 */
	public static int px2dip(Context context, float pxValue) {

		final float scale = context.getResources().getDisplayMetrics().density;

		return (int) (pxValue / scale + 0.5f);

	}

	/**
	 * 将px值转换为sp值，保证文字大小不变
	 *
	 * @param pxValue
	 * @param context （DisplayMetrics类中属性scaledDensity）
	 * @return
	 */
	public static int px2sp(Context context, float pxValue) {

		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / fontScale + 0.5f);
	}

	/**
	 * 将sp值转换为px值，保证文字大小不变
	 *
	 * @param spValue
	 * @param context （DisplayMetrics类中属性scaledDensity）
	 * @return
	 */
	public static int sp2px(Context context, float spValue) {

		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	/**
	 * 得到设备屏幕的宽度
	 */
	public static int getScreenWidth(Context context) {
		return context.getResources().getDisplayMetrics().widthPixels;
	}

	/**
	 * 得到设备屏幕的高度
	 */
	public static int getScreenHeight(Context context) {
		return context.getResources().getDisplayMetrics().heightPixels;
	}

	/**
	 * 得到设备的密度
	 */
	public static float getScreenDensity(Context context) {
		return context.getResources().getDisplayMetrics().density;
	}

	/**
	 * 判定输入汉字
	 *
	 * @param c
	 * @return
	 */
	public boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判定输入字母数字
	 *
	 * @param c
	 * @return
	 */
	public boolean isLetterOrNumber(char c) {
		String textMatcher2 = "^[A-Za-z0-9]+$";//字母数字
		if (String.valueOf(c).matches(textMatcher2)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断手机号是否合法
	 *
	 * @param s
	 * @return
	 */
	public static boolean isMobileNO(CharSequence s) {
		Pattern p = Pattern
				.compile("^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))\\d{8}$");
		// .compile("^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))//d{8}$");
		Matcher m = p.matcher(s);
		return m.matches();
	}




	public static String getCurrentTime(String strFormat) {
		SimpleDateFormat df = new SimpleDateFormat(strFormat);
		return df.format(new Date());
	}

	/**
	 * 获取app版本名称
	 * @param context
	 * @return
     */
	public static String getAPPVersionName(Context context) {
		//获取包管理器
		PackageManager pm = context.getPackageManager();
		//获取包信息
		try {
			PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取app版本名称
	 * @param context
	 * @return
	 */
	public static int getAPPVersion(Context context) {
		//获取包管理器
		PackageManager pm = context.getPackageManager();
		//获取包信息
		try {
			PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 每隔四位增加一个空格
	 */
	public static String setSpacePerFourChar(String num) {
		StringBuffer stringBuffer = new StringBuffer(num);
		int index;
		for (int i = 0; i < stringBuffer.length(); i++) {
			if ((i == 4 || i == 9 || i == 14 || i == 19)) {
				stringBuffer.insert(i, ' ');
			}
		}
		return stringBuffer.toString();
	}

	/**
	 * // 小数点左侧每三位一个逗号 保留两位小数
	 *
	 * @param data
	 * @return
	 */
	public static String formatTosepara(float data) {

		DecimalFormat df = new DecimalFormat("#,###.00");
		return df.format(data);
	}

	public static String formatTosepara(int card_on) {

		DecimalFormat df = new DecimalFormat("#,###.00");
		return df.format(card_on);
	}

	/**
	 * 隐藏手机号中间四位
	 *
	 * @param phoneNumber
	 * @return
	 * @throws RuntimeException
	 */
	public static String changeMoblie(String phoneNumber)
			throws RuntimeException {

		if (phoneNumber == null || phoneNumber.length() != 11) {
			throw new RuntimeException("手机号码长度错误");
		}

		return phoneNumber.substring(0, 3) + "****"
				+ phoneNumber.substring(7, phoneNumber.length());
	}

	/**
	 * 获取当前屏幕截图，包含状态栏
	 *
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithStatusBar(Activity activity) {
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		int height = dm.heightPixels;
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
		view.destroyDrawingCache();
		return bp;

	}

	/**
	 * 获取当前屏幕截图，不包含状态栏
	 *
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithoutStatusBar(Activity activity) {
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		Rect frame = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		int height = dm.heightPixels;
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
				- statusBarHeight);
		view.destroyDrawingCache();
		return bp;
	}


	/**
	 * 获得状态栏的高度
	 *
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context) {

		int statusHeight = -1;
		try {
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 计算虚拟键高度, 匹配虚拟键手机
	 */
	public static void setVirtualDimension( Context context) {

		int screenHeight;//屏幕高度
		int screenWidth;//屏幕高度

		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		display.getMetrics(metrics);

		DisplayMetrics dm = new DisplayMetrics();

		@SuppressWarnings("rawtypes")
		Class c;
		try {
			c = Class.forName("android.view.Display");
			@SuppressWarnings("unchecked")
			Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
			method.invoke(display, dm);
			screenHeight = dm.heightPixels;
			screenWidth = dm.widthPixels;
		} catch (Exception e) {
			screenHeight = dm.heightPixels;
			screenWidth = dm.widthPixels;
		}

		int widthPixels =  metrics.widthPixels;//除去虚拟键的屏幕高度
		int heightPixels =  metrics.heightPixels;//除去虚拟键的屏幕高度
//		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
//		params.setMargins(0,0,0,(screenHeight - heightPixels));
//		view.setLayoutParams(params);
	}
}
